package com.alan.netty.rpc.common.serialize;

import com.alan.netty.rpc.common.RpcException;
import com.alan.netty.rpc.common.Serializer;
import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;

import java.io.IOException;

/**
 * @author weiBin
 */
public class ProtoBuffSerialize implements Serializer {

    @Override
    public <T> byte[] serialize(T obj) {
        Codec<T> codec = ProtobufProxy.create((Class<T>) obj.getClass(), false);
        try {
            return codec.encode(obj);
        } catch (IOException e) {
            throw new RpcException(e.getMessage(), e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        Codec<T> codec = ProtobufProxy.create(clazz, false);
        try {
            return codec.decode(bytes);
        } catch (IOException e) {
            throw new RpcException(e.getMessage(), e);
        }
    }
}